<template>
  <div class="profile-container">
    <el-card>
      <template #header>
        <div class="profile-header">
          <h2>个人资料</h2>
        </div>
      </template>
      
      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
        class="profile-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileForm.username" disabled />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="profileForm.phoneNumber" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="profileForm.gender">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
                <el-radio :label="2">保密</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input v-model="profileForm.address" type="textarea" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="mt-20">
      <template #header>
        <div class="profile-header">
          <h2>修改密码</h2>
        </div>
      </template>
      
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        class="password-form"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            placeholder="请输入当前密码"
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码"
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="updatePassword">修改密码</el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="mt-20">
      <template #header>
        <div class="profile-header">
          <h2>常用收货地址</h2>
          <el-button type="primary" @click="addAddress">
            <el-icon><Plus /></el-icon> 新增地址
          </el-button>
        </div>
      </template>
      
      <div v-if="addressList.length > 0">
        <div v-for="(address, index) in addressList" :key="index" class="address-item">
          <div class="address-content">
            <div class="address-info">
              <div class="address-name">
                <span>{{ address.name }}</span>
                <span class="address-phone">{{ address.phone }}</span>
              </div>
              <div class="address-detail">{{ address.detail }}</div>
            </div>
            
            <div class="address-actions">
              <el-button type="primary" link @click="editAddress(index)">
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-button type="danger" link @click="removeAddress(index)">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
              <el-button 
                v-if="!address.isDefault" 
                type="success" 
                link 
                @click="setDefaultAddress(index)"
              >
                设为默认
              </el-button>
              <el-tag v-else type="success" size="small">默认地址</el-tag>
            </div>
          </div>
        </div>
      </div>
      
      <el-empty v-else description="暂无收货地址" />
    </el-card>
    
    <!-- 地址表单对话框 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="addressForm.id ? '编辑地址' : '新增地址'"
      width="500px"
    >
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressRules"
        label-width="80px"
      >
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收货人姓名" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="addressForm.detail" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认收货地址</el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddressForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { getUserProfile, updateUserProfile, updateUserPassword } from '@/api/user'

// 表单引用
const profileFormRef = ref()
const passwordFormRef = ref()
const addressFormRef = ref()

// 个人资料表单
const profileForm = ref({
  username: '',
  phoneNumber: '',
  gender: 0,
  email: '',
  address: ''
})

// 个人资料表单校验规则
const profileRules = {
  phoneNumber: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 地址列表
const addressList = ref([])

// 地址对话框可见性
const addressDialogVisible = ref(false)

// 地址表单
const addressForm = ref({
  id: '',
  name: '',
  phone: '',
  detail: '',
  isDefault: false
})

// 地址表单校验规则
const addressRules = {
  name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 获取用户信息
onMounted(() => {
  getUserInfo()
  getAddressList()
})

// 获取用户信息
const getUserInfo = async () => {
  try {
    // 调用获取用户信息API
    const res = await getUserProfile()
    
    if (res) {
      profileForm.value = res
    } else {
      // 从本地存储获取用户信息
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr)
          profileForm.value = {
            username: userInfo.username || '',
            phoneNumber: userInfo.phoneNumber || '',
            gender: userInfo.gender !== undefined ? userInfo.gender : 0,
            email: userInfo.email || '',
            address: userInfo.address || ''
          }
        } catch (error) {
          console.error('解析用户信息失败', error)
        }
      }
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    ElMessage.error('获取用户信息失败，请稍后再试')
    
    // 从本地存储获取用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        profileForm.value = {
          username: userInfo.username || '',
          phoneNumber: userInfo.phoneNumber || '',
          gender: userInfo.gender !== undefined ? userInfo.gender : 0,
          email: userInfo.email || '',
          address: userInfo.address || ''
        }
      } catch (error) {
        console.error('解析用户信息失败', error)
      }
    }
  }
}

// 获取地址列表
const getAddressList = () => {
  // 从本地存储获取地址列表
  const addressListStr = localStorage.getItem('addressList')
  if (addressListStr) {
    try {
      addressList.value = JSON.parse(addressListStr)
    } catch (error) {
      console.error('解析地址列表失败', error)
      addressList.value = []
    }
  } else {
    // 模拟数据
    addressList.value = [
      {
        id: '1',
        name: '张三',
        phone: '13800138000',
        detail: '北京市海淀区中关村大街1号',
        isDefault: true
      },
      {
        id: '2',
        name: '李四',
        phone: '13900139000',
        detail: '北京市朝阳区建国路2号',
        isDefault: false
      }
    ]
    // 保存到本地存储
    localStorage.setItem('addressList', JSON.stringify(addressList.value))
  }
}

// 提交个人资料表单
const submitForm = () => {
  profileFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用更新用户信息API
        await updateUserProfile(profileForm.value)
        ElMessage.success('个人资料更新成功')
        
        // 更新本地存储的用户信息
        const userInfoStr = localStorage.getItem('userInfo')
        if (userInfoStr) {
          try {
            const userInfo = JSON.parse(userInfoStr)
            const updatedUserInfo = {
              ...userInfo,
              phoneNumber: profileForm.value.phoneNumber,
              gender: profileForm.value.gender,
              email: profileForm.value.email,
              address: profileForm.value.address
            }
            localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
          } catch (error) {
            console.error('更新本地用户信息失败', error)
          }
        }
      } catch (error) {
        console.error('更新个人资料失败', error)
        ElMessage.error('更新个人资料失败，请稍后再试')
        
        // 模拟更新成功
        setTimeout(() => {
          ElMessage.success('个人资料更新成功')
          
          // 更新本地存储的用户信息
          const userInfoStr = localStorage.getItem('userInfo')
          if (userInfoStr) {
            try {
              const userInfo = JSON.parse(userInfoStr)
              const updatedUserInfo = {
                ...userInfo,
                phoneNumber: profileForm.value.phoneNumber,
                gender: profileForm.value.gender,
                email: profileForm.value.email,
                address: profileForm.value.address
              }
              localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
            } catch (error) {
              console.error('更新本地用户信息失败', error)
            }
          }
        }, 500)
      }
    }
  })
}

// 重置个人资料表单
const resetForm = () => {
  profileFormRef.value.resetFields()
  getUserInfo()
}

// 更新密码
const updatePassword = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用更新密码API
        await updateUserPassword({
          oldPassword: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword
        })
        ElMessage.success('密码修改成功，请重新登录')
        // 清空表单
        resetPasswordForm()
      } catch (error) {
        console.error('修改密码失败', error)
        ElMessage.error('修改密码失败，请稍后再试')
        
        // 模拟修改成功
        setTimeout(() => {
          ElMessage.success('密码修改成功')
          // 清空表单
          resetPasswordForm()
        }, 500)
      }
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}

// 新增地址
const addAddress = () => {
  addressForm.value = {
    id: '',
    name: '',
    phone: '',
    detail: '',
    isDefault: false
  }
  addressDialogVisible.value = true
}

// 编辑地址
const editAddress = (index) => {
  const address = addressList.value[index]
  addressForm.value = { ...address }
  addressDialogVisible.value = true
}

// 删除地址
const removeAddress = (index) => {
  ElMessageBox.confirm('确定要删除该收货地址吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    addressList.value.splice(index, 1)
    // 保存到本地存储
    localStorage.setItem('addressList', JSON.stringify(addressList.value))
    ElMessage.success('地址删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 设为默认地址
const setDefaultAddress = (index) => {
  // 将所有地址设为非默认
  addressList.value.forEach(item => {
    item.isDefault = false
  })
  // 将选中的地址设为默认
  addressList.value[index].isDefault = true
  // 保存到本地存储
  localStorage.setItem('addressList', JSON.stringify(addressList.value))
  ElMessage.success('已设为默认地址')
}

// 提交地址表单
const submitAddressForm = () => {
  addressFormRef.value.validate((valid) => {
    if (valid) {
      if (addressForm.value.id) {
        // 编辑地址
        const index = addressList.value.findIndex(item => item.id === addressForm.value.id)
        if (index !== -1) {
          // 如果设为默认地址，需要将其他地址设为非默认
          if (addressForm.value.isDefault) {
            addressList.value.forEach(item => {
              item.isDefault = false
            })
          }
          addressList.value[index] = { ...addressForm.value }
        }
      } else {
        // 新增地址
        const newAddress = {
          ...addressForm.value,
          id: Date.now().toString() // 生成唯一ID
        }
        
        // 如果设为默认地址，需要将其他地址设为非默认
        if (newAddress.isDefault) {
          addressList.value.forEach(item => {
            item.isDefault = false
          })
        }
        
        // 如果是第一个地址，自动设为默认
        if (addressList.value.length === 0) {
          newAddress.isDefault = true
        }
        
        addressList.value.push(newAddress)
      }
      
      // 保存到本地存储
      localStorage.setItem('addressList', JSON.stringify(addressList.value))
      
      // 关闭对话框
      addressDialogVisible.value = false
      ElMessage.success('地址保存成功')
    }
  })
}
</script>

<style scoped>
.profile-container {
  padding: 20px 0;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-header h2 {
  margin: 0;
}

.profile-form,
.password-form {
  max-width: 800px;
  margin: 0 auto;
}

.mt-20 {
  margin-top: 20px;
}

.address-item {
  padding: 15px;
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  transition: all 0.3s;
}

.address-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.address-info {
  flex: 1;
}

.address-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.address-phone {
  margin-left: 15px;
  color: #606266;
}

.address-detail {
  color: #606266;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .address-content {
    flex-direction: column;
  }
  
  .address-actions {
    margin-top: 10px;
  }
}
</style>